import java.util.ArrayList;
import java.util.List;

public class AddTwoNumbers2 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        List<Integer> list1 = new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();
        ListNode temp = l1;
        while (temp != null) {
            list1.add(temp.val);
            temp = temp.next;
        }
        temp = l2;
        while (temp != null) {
            list2.add(temp.val);
            temp = temp.next;
        }
        int p1 = list1.size() - 1;
        int p2 = list2.size() - 1;
        temp = null;
        int other = 0;
        for (; p1 >= 0 || p2 >= 0; --p1, --p2) {
            int sum = other;
            if (p1 >= 0) sum += list1.get(p1);
            if (p2 >= 0) sum += list2.get(p2);
            int cur = sum % 10;
            other = sum / 10;
            ListNode node = new ListNode(cur);
            node.next = temp;
            temp = node;
        }
        if (other != 0) {
            ListNode node = new ListNode(1);
            node.next = temp;
            temp = node;
        }
        return temp;
    }
}
